#include "profilemanager.h"

#include <QNetworkRequest>
#include <QNetworkReply>
#include "avatarmanager.h"
#include "imageprocessor.h"

namespace ImageDownload {

ProfileManager* ProfileManager::m_instance = 0;

ProfileManager* ProfileManager::instance(QObject *parent)
{
    if (!m_instance) {
        m_instance = new ProfileManager(parent);
    }
    return m_instance;
}

ProfileManager::ProfileManager(QObject *parent) :
        QObject( parent )
{
    m_imageCache.setMaxCost(300);
}

ProfileManager::~ProfileManager()
{
    m_instance = 0;
}

void ProfileManager::imageGet(const QString &imageUrl)
{
    if (m_imageCache.contains(imageUrl)) {
        emit imageReadyForUrl(imageUrl, m_imageCache[imageUrl]);
        emit imageReady();
        return;
    }

    QUrl url(imageUrl);
    QString host(url.host());
    QNetworkRequest request(url);

    if ( !m_connections.contains(host)) {
        m_connections.insert(host, new QNetworkAccessManager(this));
        connect(m_connections[host], SIGNAL(finished(QNetworkReply*)), this, SLOT(requestFinished(QNetworkReply*)));
    }

    m_connections[host]->get(request);
    m_imageCache.insert(imageUrl, new QPixmap);
}

bool ProfileManager::contains(const QString &imageUrl) const
{
    return m_imageCache.contains(imageUrl);
}

QPixmap* ProfileManager::imageFromUrl(const QString &imageUrl) const
{
    return m_imageCache[imageUrl];
}

void ProfileManager::requestFinished(QNetworkReply *reply)
{
    int replyCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();

    if (replyCode != 200)
        return;

    QPixmap *pixmap = new QPixmap;
    pixmap->loadFromData(reply->readAll());
    m_imageCache.insert(reply->url().toString(), pixmap);
    emit imageReadyForUrl(reply->url().toString(), pixmap);
    emit imageReady();
}

}
